<template>
  <div id="wangeditor">
    <div ref="editorElem" style="text-align:left"></div>
  </div>
</template>
<script>
import E from 'wangeditor'
// import { getCredential } from '@/api/upload'
import COS from 'cos-js-sdk-v5'
import uuid from '../../../../utils/uuid'
export default {
  name: 'Editor',
  data() {
    return {
      editorContent: '',
      editor: null
    }
  },
  props: ['catchData', 'value'], //接收父组件的方法
  watch: {
    value(newVal){
         this.setHtml(newVal)
    }
  },
  created() {
    this.cos = new COS({
      getAuthorization: (options, callback) => {
        getCredential().then(res => {
          if (res.success) {
            const { result } = res
            callback({
              TmpSecretId: result.tmpSecretId,
              TmpSecretKey: result.tmpSecretKey,
              XCosSecurityToken: result.sessionToken,
              ExpiredTime: result.expiredTime
            })
          } else {
            this.$message.error(res.msg)
          }
        })
      }
    })
  },
  mounted() {
    const that = this
    this.editor = new E(this.$refs.editorElem)
    //创建富文本实例
    this.editor.customConfig.onchange = html => {
      // html  带P标签的文本
      // this.getText() 不带P标签的文本
      html = this.getText()
      this.editorContent = html
      this.$emit('change')
      this.$emit('input', html)
    }
    // 隐藏“网络图片”tab
    this.editor.customConfig.showLinkImg = false
    this.editor.customConfig.uploadImgServer = '你的上传图片的接口'
    this.editor.customConfig.uploadFileName = '你自定义的文件名'
    this.editor.customConfig.uploadImgHeaders = {
      Accept: '*/*'
      // 'Authorization':'Bearer ' + token    //头部token
    }
    this.editor.customConfig.menus = [
      //菜单配置
      'head',
      'list', // 列表
      'justify', // 对齐方式
      'bold',
      'fontSize', // 字号
      'italic',
      'underline',
      //'image', // 插入图片
      'foreColor', // 文字颜色
      'undo', // 撤销
      'redo' // 重复
    ]
    //下面是最重要的的方法
    this.editor.customConfig.customUploadImg = function(files, insert) {
      console.log('图片上传', files)
      const file = files[0]
      const uid = uuid(32)
      const extName = that.getExtName(file.name)
      const fileName = `${uid}.${extName}`
      that.cos.sliceUploadFile(
        {
          Bucket: that.$CONFIG.Bucket,
          Region: that.$CONFIG.Region,
          Key: fileName,
          Body: file
        },
        (err, data) => {
          if (!err) {
            const { Location } = data
            const imageUrl = 'http://' + Location
            insert(imageUrl)
          }
        }
      )
    }
    this.editor.create()
    if (this.value) {
      this.setHtml(this.value)
    }
  },
  methods: {
    // 获取内容(html)
    getHtml() {
      return this.editor.txt.html()
    },
    // 获取内容(纯文本)
    getText() {
      return this.editor.txt.text()
    },
    // 设置内容(html)
    setHtml(text) {
      this.editor.txt.html(text)
    },
    // 追加内容(html)
    appendHtml(text) {
      this.editor.txt.append(text)
    },
    // 清空内容
    clear() {
      this.editor.txt.clear()
    },
    /**
     * 获取后缀名
     */
    getExtName(fileName) {
      let index = fileName.lastIndexOf('.')
      if (index > -1) {
        return fileName.substring(index + 1)
      } else {
        return ''
      }
    }
   }
}
</script>
<style lang="less">
.w-e-toolbar {
  flex-wrap: wrap !important;
}
.w-e-text {
  p {
    white-space: normal !important;
  }
}
</style>